package com.wuyan.locationdog.ui.map

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.viewModels
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.offlinemap.OfflineMapActivity
import com.arcsoft.commonbase.base.BaseBindingFragment
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_device_info_modify
import com.arcsoft.commonbase.bus.bus_logout
import com.arcsoft.commonbase.bus.bus_refresh_style
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.arcsoft.commonbase.ext.radius
import com.arcsoft.commonbase.ext.visible
import com.blankj.utilcode.util.ActivityUtils
import com.wuyan.locationdog.databinding.DeviceHomeFragmentBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.DogHelp
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.ui.compass.OneDeviceCompassActivity
import com.wuyan.locationdog.ui.device.DeviceFenceListActivity
import com.wuyan.locationdog.ui.device.DogAddFilesActivity
import com.wuyan.locationdog.ui.device.DogFilesDetailActivity
import com.wuyan.locationdog.ui.device.DogFilesListActivity
import com.wuyan.locationdog.ui.device.FlowDetailActivity
import com.wuyan.locationdog.ui.device.MapDeviceDetailActivity
import com.wuyan.locationdog.ui.login.RegisterActivity
import com.wuyan.locationdog.ui.my.MarkListActivity
import com.wuyan.locationdog.ui.my.MyAlarmSetActivity
import com.wuyan.locationdog.ui.my.MyOrderActivity
import com.wuyan.locationdog.ui.my.SetActivity
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.util.maputil.setDeviceDetailStatus
import com.wuyan.locationdog.viewmodel.DeviceViewModel


class DeviceHomeFragment : BaseBindingFragment<DeviceHomeFragmentBinding>() {
    private val mViewModel: DeviceViewModel by viewModels()
    override fun onCreateViewBind(savedInstanceState: Bundle?) {
        super.onCreateViewBind(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding.mapView, savedInstanceState))
    }

    override fun lazyLoadData() {
        binding.apply {
            mapView.radius(8F)

            initLocation()

            btnCancel.setOnClickListener {
                msgLayout.gone()
            }
            btnGo.setOnClickListener {
                val bundle = Bundle()
                bundle.putInt("type", 8)
                bundle.putBoolean("isBindPhone", true)
                ActivityUtils.startActivity(bundle, RegisterActivity::class.java)
            }
            btnDeviceSet.setOnClickListener {
                ActivityUtils.startActivity(SetActivity::class.java)
            }
        }
    }

    override fun loadNetData() {
        super.loadNetData()

        val map = HashMap<String, Any>()
        map["imei"] = LoginHelp.imei
        mViewModel.mapDeviceLocation(map)
    }

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
//                val latLng = LatLng(amapLocation.latitude, amapLocation.longitude)
//                binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))

                if (isLoadNetFinish) {
                    val latLng =
                        LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)
                    binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))
                }

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "map",
                    "location Error, ErrCode:" + amapLocation.errorCode + ", errInfo:" + amapLocation.errorInfo
                )
            }
        }
    }

    private fun initLocation() {
        //初始化AMapLocationClientOption对象
        val mLocationOption = AMapLocationClientOption().apply {
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            //设置定位间隔,单位毫秒,默认为2000ms
            interval = 2000
            isOnceLocation = true
        }
        val mLocationClient = AMapLocationClient(context).apply {
            //设置定位回调监听
            setLocationListener(mLocationListener)
            //给定位客户端对象设置定位参数f
            setLocationOption(mLocationOption)
            //启动定位
            startLocation()
        }
    }

    override fun observe() {
        super.observe()
        Bus.observe<String>(bus_logout, this) {
            LoginHelp.logout()
        }
        Bus.observe<String>(bus_device_info_modify, this) {
            loadNetData()
        }
        Bus.observe<String>(bus_refresh_style, this) {
            loadNetData()
        }
        mViewModel.deviceDetailBean.observe(this) {
            val deviceBeanContent = it.content
            DeviceHelp.selectDeviceBeanContent = deviceBeanContent

            binding.apply {
                if (it.content.compositeDetailStatus == 5) {
                    goServiceLayout.visible()
                    desc.text = "使用监控服务，需要激活设备"
                } else if (it.content.compositeDetailStatus == 6) {
                    goServiceLayout.visible()
                    desc.text =
                        "您的云服务已过期" + it.content.expirationDay + "天，为了不中断您所依赖的重要功能和优质体验，请前往充值。"
                } else {
                    goServiceLayout.gone()
                }
                mapView.map.clear(true)
                MapHelp.getMarkerUi(layoutInflater, deviceBeanContent) {
                    mapView.map.addMarker(it)
                }

                val latLng =
                    LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)

                binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))
                deviceName.text = DeviceHelp.getDeviceName(deviceBeanContent)
                imei.text = "设备ID：" + deviceBeanContent.imei

                if (deviceBeanContent.deviceDetailVO.userPhone.isNullOrEmpty()) {
                    msgLayout.visible()
                } else {
                    msgLayout.gone()
                }

                ivStatus.setDeviceDetailStatus(it.content.compositeDetailStatus)
                ivCar.loadImageCircleCar(it.content.dog?.dogImg)

                val bundle = Bundle()
                bundle.putSerializable("DeviceBeanContent", deviceBeanContent)

                btnBigMap.setOnClickListener {
                    ActivityUtils.startActivity(bundle, MapDeviceDetailActivity::class.java)
                }

                mapView.map.setOnMapClickListener {
                    btnBigMap.callOnClick()
                }
                btnOffLineMap.setOnClickListener {
                    ActivityUtils.startActivity(OfflineMapActivity::class.java)
                }
                btnSure.setOnClickListener {
                    ActivityUtils.startActivity(bundle, FlowDetailActivity::class.java)
                }
                btnCompass.setOnClickListener {
                    ActivityUtils.startActivity(OneDeviceCompassActivity::class.java)
                }
                btnDogFiles.setOnClickListener {
//                    DogHelp.mDogFileBeanContent = deviceBeanContent.dog
//                    DogHelp.isModifyDogFile = !deviceBeanContent.dog?.dogId.isNullOrEmpty()
//                    ActivityUtils.startActivity(DogAddFilesActivity::class.java)
                    DogHelp.isGoDetail = true
                    ActivityUtils.startActivity(DogFilesListActivity::class.java)
                }
                btnFenceManage.setOnClickListener {
                    ActivityUtils.startActivity(DeviceFenceListActivity::class.java)
                }
                btnAlarmSet.setOnClickListener {
                    ActivityUtils.startActivity(MyAlarmSetActivity::class.java)
                }

                btnMark.setOnClickListener {
                    ActivityUtils.startActivity(MarkListActivity::class.java)
                }
                btnMyOrder.setOnClickListener {
                    ActivityUtils.startActivity(MyOrderActivity::class.java)
                }
            }


            isLoadNetFinish = true
        }
    }

}